package com.github.fashionbrot.interceptor;

import com.github.fashionbrot.PermissionMethod;
import com.github.fashionbrot.Token;
import com.github.fashionbrot.TokenMethod;
import com.github.fashionbrot.common.util.ObjectUtil;
import com.github.fashionbrot.common.util.SetUtil;
import com.github.fashionbrot.exception.AuthException;
import com.github.fashionbrot.exception.InvalidTokenException;
import com.github.fashionbrot.exception.SignatureVerificationException;
import com.github.fashionbrot.exception.TokenExpiredException;
import com.github.fashionbrot.function.*;
import com.github.fashionbrot.service.ExampleService;
import com.github.fashionbrot.util.AuthUtil;
import com.github.fashionbrot.util.PermissionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Optional;

@Slf4j
@Component
public class ExampleInterceptor implements HandlerInterceptor {

    @Resource
    private ExampleService exampleService;

    private static boolean test(String[] permissions) {
        for (String permission : permissions) {
            if (permission.equals("test1")) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        Token token = TokenMethod.decrypt(exampleService.getAlgorithm(), Token.class,"token");
        if (token == null || token.getUserId() == null) {
            AuthException.throwMsg("未登录");
            return true;
        }

        boolean flag = PermissionMethod.isPermission(handler, ExampleInterceptor::test);
        if (!flag) {
            AuthException.throwMsg("没有权限");
        }


        return true;
    }


}
